let currentPage = 1;
const pageSize = 50; // 每页显示的数据量
const totalPages = 72; // 总页数，实际应用中可能需要从API获取

document.addEventListener('DOMContentLoaded', function() {
    setupPagination();
    fetchProblems(currentPage, pageSize);
});

function setupPagination() {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = ''; // 清空现有内容

    // 添加上一页按钮
    addPageButton('«', () => changePage(currentPage - 1));

    // 添加数字页面按钮
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            addPageButton(i, () => changePage(i));
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            addPageButton('...', null);
        }
    }

    // 添加下一页按钮
    addPageButton('»', () => changePage(currentPage + 1));

    updateActiveButton();
}

function addPageButton(text, onClick) {
    const button = document.createElement('button');
    button.textContent = text;
    if (onClick) {
        button.addEventListener('click', onClick);
    } else {
        button.disabled = true;
    }
    document.getElementById('pagination').appendChild(button);
}

function changePage(newPage) {
    if (newPage >= 1 && newPage <= totalPages) {
        currentPage = newPage;
        updateActiveButton();
        fetchProblems(currentPage, pageSize);
    }
}

function updateActiveButton() {
    const buttons = document.querySelectorAll('#pagination button');
    buttons.forEach(button => {
        button.classList.toggle('active', button.textContent === currentPage.toString());
    });
}

function fetchProblems(page, size) {
    // 这里应该是实际的 API 调用
    console.log(`Fetching problems: page ${page}, size ${size}`);

    // 模拟 API 调用
    fetch(`http://127.0.0.1:5000/problem/getAll`)
        .then(response => response.json())
        .then(data => {
            updateProblemList(data);
        })
        .catch(error => {
            console.error('Error fetching problems:', error);
        });
}

function updateProblemList(problems) {
    const tableBody = document.querySelector('#problem-table tbody');
    tableBody.innerHTML = ''; // 清空现有内容

    problems.forEach(problem => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>□</td>
            <td>${problem.id}</td>
            <td><a href="/question/do?id=${problem.id}" class="problem-link">${problem.title}</a></td>
            <td>${problem.level}</td>
            <td>⭐</td>
        `;
        tableBody.appendChild(row);
    });
}